// 数组列表转换为树结构列表
// rootId主动设置根节点id为rootId
export function arr2Tree(arr, params, resObj = []) {
  let {
    id = "id",
    parentId = "parentId",
    children = "children",
    rootId,
  } = params || {};
  console.log(id, parentId, children, "");
  const mapObj = new Map();
  let element, operateObj;
  for (let index = 0; index < arr.length; index++) {
    element = arr[index];
    if (!mapObj.has(element[id])) {
      mapObj.set(element[id], element);
    }
    // 判断是不是根节点
    if (!element[parentId] || (rootId && element[parentId] === rootId)) {
      resObj.push(element);
    }
  }
  for (let index = 0; index < arr.length; index++) {
    element = arr[index];
    if (mapObj.has(element[parentId])) {
      operateObj = mapObj.get(element[parentId]);
      operateObj[children] = [
        ...new Set((operateObj[children] || []).concat(element)),
      ];
    }
    operateObj = null;
  }
  console.log(resObj, "arr2Tree*----------");
  return resObj;
}

// 在树形数组中寻找目标值，返回该项
export function findInTree(params) {
  const {
    tree,
    targetKey,
    targetValue,
    getPath = false, // 获取递归路径
    saveArr = [], // 路径盒子
    childrenName = "children",
  } = params || {};
  for (let node of tree) {
    if (node[targetKey] === targetValue) {
      getPath && saveArr.push(node);
      return node;
    }
    if (node[childrenName]) {
      let result = findInTree({
        ...params,
        tree: node[childrenName],
        saveArr,
      });
      if (result) {
        getPath && saveArr.push(node);
        return { result, saveArr };
      }
    }
  }
  return null;
}

// 防抖
export function debounce(func, delay, immediate = false) {
  let timeoutId;

  return function () {
    const context = this;
    const args = arguments;

    const later = function () {
      timeoutId = null;
      if (!immediate) {
        func.apply(context, args);
      }
    };

    const callNow = immediate && !timeoutId;

    clearTimeout(timeoutId);
    timeoutId = setTimeout(later, delay);

    if (callNow) {
      func.apply(context, args);
    }
  };
}
//fn执行函数 delay停止触发事件多长时间后执行函数 minTime不断触发时强制执行时间
export function throttle(fn, delay = 0, minTime = 1000) {
  let timer = null;
  let t_start;
  return function () {
    let context = this,
      args = arguments,
      t_curr = +new Date();
    clearTimeout(timer);
    if (!t_start) {
      t_start = t_curr;
    }
    if (t_curr - t_start >= minTime) {
      fn.apply(context, args);
      t_start = t_curr;
    } else {
      timer = setTimeout(function () {
        fn.apply(context, args);
      }, delay);
    }
  };
}

// 图片转base64字符串
export function imgDom2Base64(imgDom, useNatural = true) {
  if (!imgDom) return null;
  // 创建一个Canvas元素
  const canvas = document.createElement("canvas");
  const ctx = canvas.getContext("2d");

  // 设置Canvas尺寸与图片尺寸一致
  canvas.width = useNatural ? imgDom.naturalWidth : imgDom.width;
  canvas.height = useNatural ? imgDom.naturalHeight : imgDom.height;

  // 在Canvas上绘制图片
  ctx.drawImage(imgDom, 0, 0);

  // 将Canvas内容转换为base64编码
  const base64 = canvas.toDataURL("image/png");

  return base64;
}

export function getParameter(sProp) {
  if (document.location.search) {
    let re = new RegExp(sProp + "=([^&]*)", "i");
    let a = re.exec(document.location.search);
    if (a == null) return null;
    return a[1];
  }
  return null;
}

export function setKeyValue({ key, value }) {
  this[key] = value;
}

// 获取当前数值下的等比例值
// 100的值为50的话，传入value=50，old为100，now为10，返回值应该是5
export function convertByRatio(value, ratioOrRect) {
  const ratio =
    typeof ratioOrRect === "number"
      ? ratioOrRect
      : ratioOrRect.now / ratioOrRect.old;
  return value * ratio;
}

export function polifillMiniBlinkCreateObjectURL(file) {
  return new Promise((resolve, reject) => {
    try {
      if (URL.createObjectURL) {
        resolve(URL.createObjectURL(file));
      } else {
        // 读取文件
        const reader = new FileReader();
        reader.onload = (e) => {
          resolve(e.target.result);
        };
        reader.onerror = reject;
        // 以DataURL格式读取文件
        reader.readAsDataURL(file);
      }
    } catch (error) {
      reject(error);
    }
  });
}

export const isDef = (obj) => {
  if (obj === null || obj === void 0) {
    return false;
  }
  return true;
};

//listData每一项的valProp设置值
//prop为数组就是求和，没有做递归求和
//prop为xxxx.xx就是层级求值
export function setPropVal(listData = [], originData = {}, valProp) {
  if (!Array.isArray(listData)) {
    return;
  }
  listData.forEach((cardItem) => {
    if (Array.isArray(cardItem)) {
      setPropVal(cardItem, originData, valProp);
    } else {
      if (Array.isArray(cardItem.prop)) {
        cardItem[valProp] = cardItem.prop.reduce((pre, next) => {
          pre += originData[next];
          return pre;
        }, 0);
      } else {
        let propsArr = (cardItem.prop || "")
          .split(".")
          .filter((item) => isDef(item));
        let propVal,
          linshiObj = originData,
          linshiProp;
        while (propsArr.length) {
          if (isDef((linshiProp = propsArr.shift()))) {
            propVal = linshiObj && linshiObj[linshiProp];
            linshiObj = propVal;
          }
        }
        cardItem[valProp] = propVal;
      }
    }
  });
}

export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null;
  }
  const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
  let date;
  if (typeof time === "undefined" || time === null || time === "null") {
    return "";
  } else if (typeof time === "object") {
    date = time;
  } else {
    if (typeof time === "string" && /^[0-9]+$/.test(time)) {
      time = parseInt(time);
    }
    if (typeof time === "number" && time.toString().length === 10) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  };
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key];
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value];
    }
    if (result.length > 0 && value < 10) {
      value = "0" + value;
    }
    return value || 0;
  });
  return time_str;
}

// 下载文件
export function downloadFile(obj, name, suffix) {
  const fileName = parseTime(new Date()) + "-" + name + "." + suffix;
  const url = window.URL.createObjectURL(new Blob([obj]));
  const link = document.createElement("a");
  link.style.display = "none";
  link.href = url;
  link.setAttribute("download", fileName);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

/** 模拟异步请求，实用性不高，主要用于demo模拟请求 */
export const waitTime = (time = 100, data = true) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(data);
    }, time);
  });
};
// 生成[min, max]随机数
export function randomNumBoth(Min, Max, params) {
  const { round = true } = params || {};
  const Range = Max - Min;
  const Rand = Math.random();
  const num = Min + (round ? Math.round(Rand * Range) : Rand * Range); //四舍五入
  return num;
}

export function pxtorem(px) {
  if (typeof px === "string") px = parseInt(px);
  return px / 100 + "rem";
}
export function object2Enum(obj) {
  const enumObject = {};
  Object.keys(obj).forEach((key) => {
    enumObject[key] = obj[key];
    enumObject[obj[key]] = key;
  });
  return Object.freeze(enumObject);
}

//查找字典里的某一项
export function arrDicFind(val, dic, propAlias = {}) {
  const item = (dic || []).find(
    (item) =>
      item[propAlias.value || "value"] === val ||
      item[propAlias.label || "label"] === val
  );
  return item;
}
//小数点保留位数
export function floatSaveLength(val, saveFloatLength = 2, params) {
  const {
    isRound = true, //是否四舍五入
  } = params || {};
  if (typeof val !== "number") {
    val = Number(val);
  }
  let saveFloatHelper = Math.pow(10, saveFloatLength + 1);
  if (Number.isNaN(val)) {
    val = 0;
  }
  let res = Math.round(val * saveFloatHelper) / saveFloatHelper;
  if (!isRound) {
    res = Math.floor(val * saveFloatHelper) / saveFloatHelper;
  }
  return res.toFixed(saveFloatLength);
}

// 给定图片地址，获取图片原尺寸
export const getNatural = (imagePath) => {
  return new Promise((resolve, reject) => {
    if (!imagePath) {
      reject("图片地址错误");
      return;
    }
    // 获取图片标签
    const img = document.createElement("img");
    // 读取图片文件
    img.src = imagePath;
    document.body.appendChild(img);
    // 当图片加载完成时
    img.onload = () => {
      // 获取图片的宽度和高度
      const res = {
        naturalWidth: img.naturalWidth,
        naturalHeight: img.naturalHeight,
      };
      img.remove();
      resolve(res);
    };
  });
};

// 给定图片file或者图片地址，返回图片地址imgPath，图片原始尺寸naturalRect，图片字节大小charSize
// 如设置图片字节大小范围sizeRange，图片尺寸范围则会对此判断并抛出异常
// toText和textMessageList配合返回异常错误文案处理
export const getImageNaturalSize = (params) => {
  let {
    file,
    imgPath,
    sizeRange,
    rectRange,
    toText = true,
    textMessageList,
  } = params || {};
  const minSize = (sizeRange || [])[0];
  const maxSize = (sizeRange || [])[1];
  const minRect = (rectRange || [])[0];
  const maxRect = (rectRange || [])[1];
  textMessageList = textMessageList ?? {};
  return new Promise((resolve, reject) => {
    const judgeFileRes = (imgPath, charSize, type) => {
      if (/^image/.test(type)) {
        return getNatural(imgPath).then((img) => {
          // 获取图片的宽度和高度
          // 可以在这里对图片的宽度和高度进行进一步处理
          if (minSize && charSize < minSize) {
            reject(toText ? textMessageList[0] || "请上传正确的图片尺寸" : 0);
            return;
          } else if (maxSize && charSize > maxSize) {
            reject(toText ? textMessageList[1] || "请上传正确的图片尺寸" : 1);
            return;
          }
          const naturalRect = img.naturalWidth * img.naturalHeight;
          if (minRect && naturalRect < minRect) {
            reject(
              toText
                ? textMessageList[3] ||
                    `请上传${minRect || 0}≤图像分辨率${
                      maxRect ? "≤" + maxRect : ""
                    }的图片`
                : 3
            );
            return;
          } else if (maxRect && naturalRect > maxRect) {
            reject(
              toText
                ? textMessageList[4] ||
                    `请上传${minRect || 0}≤图像分辨率${
                      maxRect ? "≤" + maxRect : ""
                    }的图片`
                : 4
            );
            return;
          }
          resolve({
            imgPath,
            charSize, // 字节大小
            naturalRect: [img.naturalWidth, img.naturalHeight], // 真实尺寸
          });
        });
      } else {
        reject(toText ? textMessageList[5] || "请上传正确的图片格式" : 5);
      }
    };
    if (file instanceof File) {
      // 看支持不支持FileReader
      if (!file || !window.FileReader) {
        reject(toText ? textMessageList[2] || "获取图片数据时出错" : 2);
        return;
      }
      let imgPath = window.URL.createObjectURL(file) || null;
      judgeFileRes(imgPath, file.size, file.type);
    } else if (imgPath) {
      fetch(imgPath)
        .then((response) => response.blob()) // 将响应转换为 Blob 对象
        .then((blob) => {
          judgeFileRes(imgPath, blob.size, blob.type);
        })
        .catch((error) => console.error("获取图片数据时出错", error));
    }
  });
};
export const getNetworkInterfaces = () => {
  return (uuidV4 || Math.random)();
};

// export const require = (url) => {
//   // 将图片、json文件导为模块
//   const srcModules = import.meta.glob("../**/*.(json|png|jpg|jpeg)", {
//     eager: true,
//   });
//   const _url = url.replace("@", "");
//   // 获取图片模块
//   // 获取指定的图片
//   const path = `..${_url}`;
//   return srcModules[path].default;
// };
export function autoNumber(val, UIWidth = 1920) {
  const clientWidth =
    window.innerWidth ||
    document.documentElement.clientWidth ||
    document.body.clientWidth;
  if (!clientWidth) return;
  let fontSize = clientWidth / UIWidth;
  return val * fontSize;
}
